package br.com.post.persistence;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.Schooling;

public class SchoolingDao {
	private static SchoolingDao instance;
	/**
	 * Persiste a escolaridade no banco
	 * @param schooling
	 */
	public void createSchooling(Schooling schooling) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(schooling);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza a escolaridade no banco
	 * @param schooling
	 */
	public void updateSchooling(Schooling schooling) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(schooling);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona uma escolaridade no banco de acordo com o id(long)
	 * @param schooling_id
	 * @return schooling
	 */
	public Schooling selectSchooling(long schooling_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Schooling schooling = (Schooling)session.get(Schooling.class,schooling_id);
		tx.commit();
		session.close();
		return schooling;
	}
	
	/**
	 * Deleta a escolaridade de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove a escolaridade selecionada
	 * @param schooling_id
	 */
	public void deleteSchooling(long schooling_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Schooling schooling = selectSchooling(schooling_id);
		session.delete(schooling);
		tx.commit();
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<Schooling> getList() {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		List<Schooling> listSchooling = (List<Schooling>)session.createQuery("from Schooling s order by s.schooling_description").list();
		tx.commit();
		session.close();
		return listSchooling;
	}

	public static SchoolingDao getInstance() {
		if(instance==null)
			instance = new SchoolingDao();
		return instance;
	}

	public static void setInstance(SchoolingDao instance) {
		SchoolingDao.instance = instance;
	}
	
}

